#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的测试验证脚本
"""

import sys
import os
from pathlib import Path

# 添加src目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root / 'src'))

def test_imports():
    """测试模块导入"""
    try:
        from core.models import Order, Trade
        from storage.sqlalchemy_storage import SQLAlchemyStorage
        from adapters.tradingview_adapter import TradingViewAdapter
        from core.trade_processor import TradeProcessor
        print("✅ 所有模块导入成功")
        return True
    except ImportError as e:
        print(f"❌ 模块导入失败: {e}")
        return False

def test_basic_functionality():
    """测试基本功能"""
    try:
        from datetime import datetime
        from decimal import Decimal
        from core.models import Order
        
        # 创建订单
        order = Order(
            order_id="test_001",
            symbol="MESM25",
            side="buy",
            order_type="market",
            quantity=Decimal("1"),
            filled=Decimal("1"),
            quantity_left=Decimal("0"),
            avg_fill_price=Decimal("5000.00"),
            status="filled",
            open_time=datetime.now(),
            close_time=datetime.now(),
            commission=Decimal("2.50"),
            multiplier=Decimal("5")
        )
        
        assert order.order_id == "test_001"
        assert order.symbol == "MESM25"
        assert order.side == "buy"
        
        print("✅ 基本功能测试通过")
        return True
    except Exception as e:
        print(f"❌ 基本功能测试失败: {e}")
        return False

def test_storage():
    """测试存储功能"""
    try:
        import tempfile
        import os
        import shutil
        from datetime import datetime
        from decimal import Decimal
        from core.models import Order, Trade
        from storage.sqlite3_storage import SQLite3Storage
        
        # 创建临时目录
        temp_dir = tempfile.mkdtemp()
        temp_db = os.path.join(temp_dir, 'test.db')
        
        try:
            # 测试SQLite3存储
            storage = SQLite3Storage(temp_db)
            
            # 测试保存和获取订单
            test_order = Order()
            test_order.order_id = "test_001"
            test_order.symbol = "MESM25"
            test_order.side = "buy"
            test_order.order_type = "market"
            test_order.quantity = float(Decimal("1"))
            test_order.filled = float(Decimal("1"))
            test_order.quantity_left = float(Decimal("0"))
            test_order.avg_fill_price = float(Decimal("5000.00"))
            test_order.status = "filled"
            test_order.open_time = datetime(2025, 6, 14, 9, 30, 0)
            test_order.close_time = datetime(2025, 6, 14, 9, 30, 5)
            test_order.duration = "00:00:05"
            test_order.commission = float(Decimal("2.50"))
            test_order.multiplier = float(Decimal("5"))
            
            # 保存订单
            result = storage.save_orders([test_order])
            assert result['success'] == True
            assert result['saved_count'] == 1
            
            # 获取订单
            orders = storage.get_orders()
            assert len(orders) == 1
            assert orders[0].order_id == "test_001"
            assert orders[0].symbol == "MESM25"
            
            # 测试重复订单检测
            result2 = storage.save_orders([test_order])
            assert result2['success'] == True
            assert result2['duplicate_count'] == 1
            assert result2['saved_count'] == 0
            
            # 测试保存和获取交易
            test_trade = Trade()
            test_trade.trade_id = "test_trade_001"
            test_trade.symbol = "MESM25"
            test_trade.open_datetime = datetime(2025, 6, 14, 9, 30, 5)
            test_trade.open_price = 5000.00
            test_trade.open_qty = 1
            test_trade.close_datetime = datetime(2025, 6, 14, 10, 0, 5)
            test_trade.close_price = 5010.00
            test_trade.close_qty = 1
            test_trade.direction = "Long"
            test_trade.open_order_type = "market"
            test_trade.trade_type = ""
            test_trade.side = None
            test_trade.point_profit_per_lot = 10.00
            test_trade.total_points = 10.00
            test_trade.gross_profit = 50.00
            test_trade.net_profit = 45.00
            test_trade.commission = 5.00
            test_trade.holding_time = "00:30:00"
            test_trade.nth_trade = 1
            test_trade.session = "RTH"
            
            # 保存交易
            storage.save_trades([test_trade])
            
            # 获取交易
            trades = storage.get_trades()
            assert len(trades) == 1
            assert trades[0].trade_id == "test_trade_001"
            assert trades[0].symbol == "MESM25"
            assert trades[0].direction == "Long"
            assert trades[0].net_profit == 45.00
            
            # 测试更新交易
            success = storage.update_trade("test_trade_001", {
                'trade_type': 'Scalp',
                'entry_reason': 'Breakout'
            })
            assert success == True
            
            # 验证更新
            updated_trades = storage.get_trades()
            assert updated_trades[0].trade_type == 'Scalp'
            assert updated_trades[0].entry_reason == 'Breakout'
            
            # 测试删除交易
            success = storage.delete_trade("test_trade_001")
            assert success == True
            
            # 验证删除
            final_trades = storage.get_trades()
            assert len(final_trades) == 0
            
            storage.close()
            
            print("✅ 存储功能测试通过")
            print("   - 订单保存/获取: ✓")
            print("   - 重复订单检测: ✓")
            print("   - 交易保存/获取: ✓")
            print("   - 交易更新: ✓")
            print("   - 交易删除: ✓")
            return True
            
        finally:
            # 清理临时文件
            if os.path.exists(temp_dir):
                shutil.rmtree(temp_dir, ignore_errors=True)
                
    except Exception as e:
        print(f"❌ 存储功能测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_filter_functionality():
    """测试过滤功能（需要Flask应用运行）"""
    try:
        import subprocess
        import time
        import requests
        
        print("⚠️  过滤功能测试需要Flask应用运行在localhost:5000")
        print("   请确保已运行: python app.py")
        
        # 检查Flask应用是否运行
        try:
            response = requests.get('http://localhost:5000/statistics/filter_options', timeout=5)
            if response.status_code != 200:
                print("❌ Flask应用未运行或响应异常")
                return False
        except requests.exceptions.RequestException:
            print("❌ 无法连接到Flask应用，请先运行: python app.py")
            return False
        
        # 运行过滤功能测试
        result = subprocess.run([
            sys.executable, '-m', 'unittest', 'tests.test_filter_functionality', '-v'
        ], capture_output=True, text=True, cwd=project_root)
        
        if result.returncode == 0:
            print("✅ 过滤功能测试通过")
            print(result.stdout)
            return True
        else:
            print("❌ 过滤功能测试失败")
            print(result.stderr)
            return False
            
    except Exception as e:
        print(f"❌ 过滤功能测试失败: {e}")
        return False

def main():
    """运行所有测试"""
    print("开始运行测试验证...")
    print("=" * 50)
    
    tests = [
        ("模块导入", test_imports),
        ("基本功能", test_basic_functionality),
        ("存储功能", test_storage),
        ("过滤功能", test_filter_functionality)
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n🧪 测试: {test_name}")
        try:
            if test_func():
                passed += 1
            else:
                print(f"   测试失败")
        except Exception as e:
            print(f"   测试异常: {e}")
            import traceback
            traceback.print_exc()
    
    print("\n" + "=" * 50)
    print(f"测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有测试通过！测试框架准备就绪。")
        return 0
    else:
        print("⚠️  部分测试失败，请检查配置。")
        return 1

if __name__ == '__main__':
    sys.exit(main()) 